//
//  oldMyCenterHeaderView.m
//  laonianbang
//
//  Created by 勇拓 李 on 17/10/16.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "oldMyCenterHeaderView.h"
#import "UIImageView+oldImageView.h"
#import "OldAccount.h"
#import "oldNetWork.h"
#import "VPImageCropperViewController.h"
#import "oldImage.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "QNuploader.h"
#import "oldHub.h"

@interface oldMyCenterHeaderView()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *head_img;
@property (weak, nonatomic) IBOutlet UILabel *label_name;

@end

@implementation oldMyCenterHeaderView

- (void)awakeFromNib
{
    [super awakeFromNib];
    _head_img.layer.cornerRadius = 50.f;
    _head_img.layer.masksToBounds = YES;
    [self initHeader];
}

- (void)initHeader
{
    [_head_img showHeadImg:ACCOUNT_SINGLETON.accountInfo.avatar];
    _label_name.text = ACCOUNT_SINGLETON.accountInfo.uname;
    
    UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ges:)];
    [_head_img addGestureRecognizer:ges];
    _head_img.userInteractionEnabled = YES;
}

#pragma mark - 头像上传
- (void)ges:(id)sender
{
    WeakSelf
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectFormPhotos];
    }];
    
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectFormPicture];
    }];
    
    [alertController addAction:cancelAction];
    
    [alertController addAction:photoAction];
    
    [alertController addAction:pictureAction];
    
    
    [_vc presentViewController:alertController animated:YES completion:nil];
}

- (void)selectFormPhotos
{
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self.vc presentViewController:controller
                              animated:YES
                            completion:^(void){
                                NSLog(@"Picker View Controller is presented");
                            }];
    }
}

- (void)selectFormPicture
{
    // 从相册中选取
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self.vc presentViewController:controller
                              animated:YES
                            completion:^(void){
                                NSLog(@"Picker View Controller is presented");
                            }];
    }
}

- (void)editHeadImg:(UIImage *)editedImage
{
    
    [oldHub waiting:@"头像上传中.."];
    
    WeakSelf
    
    NSString *uploadurl = [oldImage getImagePath:[oldImage compressImage:editedImage ratio:1.0]];
    [QiNiuShareInstance uploadImageToQNFilePath:uploadurl type:Image_file block:^(NSString *url) {
        
        if (url) {
            [weakSelf uploadAvatar:url];
        }
        else
        {
            [oldHub warningUser:@"头像上传失败请重试"];
        }
    }];
}

- (void)uploadAvatar:(NSString *)url
{
    WeakSelf
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: url, @"avatar", nil];
    
    [OLDNetWork httpRequestWithPostPut:URL_EditProfile params:params success:^(id data) {
        [oldHub hideHUD];
        ACCOUNT_SINGLETON.accountInfo = [[oldServer alloc] initWithDictionary:data];
        [weakSelf.head_img showHeadImg:ACCOUNT_SINGLETON.accountInfo.avatar];
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [oldImage imageByScalingToMaxSize:portraitImg];
        // present the cropper view controller
        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.vc.view.frame.size.width, self.vc.view.frame.size.width) limitScaleRatio:3.0];
        imgCropperVC.delegate = self;
        [self.vc presentViewController:imgCropperVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [cropperViewController dismissViewControllerAnimated:NO completion:^{
        [self editHeadImg:editedImage];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark camera utility

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}


@end
